<template>
  <Popup v-model="show" position="bottom">
    <Cascader
      v-model="cascaderValue"
      title="请选择所在省市区"
      :field-names="fieldNames"
      :loading="isLoading"
      :options="dataRes"
      @change="onChange"
      @finish="onConfirmClick"
      @close="onCancelClick"
    />
  </Popup>
</template>

<script>
import Popup from '@/widgets/Popup'
import Cascader from '@/widgets/Cascader'
import { findTreeNodeQuickly } from '@/utils/public/obj-util'
import {
  rqtGetPlaceByType,
  rqtGetPlaceChildrenByType
} from '@/services/common/place'

export default {
  name: 'AddrDataPickerCpt',
  components: {
    Popup,
    Cascader
  },
  props: {},
  data() {
    return {
      show: false,
      isLoading: false,
      fieldNames: {
        text: 'placeName',
        value: 'placeCode',
        children: 'children'
      },
      cascaderValue: '',
      dataRes: []
    }
  },
  methods: {
    showView() {
      this.show = true
      this.isLoading = true
      const params = { placeType: '01' }
      rqtGetPlaceByType(params)
        .then(res => {
          let resData = res.data.data
          this.initChildren(resData)
          this.dataRes = resData
        })
        .catch(() => {})
    },
    initChildren(resData, children = []) {
      for (const item of resData) {
        this.initChild(item, children)
      }
    },
    initChild(item, children = []) {
      if (!item.children || !item.children.length) {
        item.children = children || []
      }
    },
    onChange(val) {
      const placeType = '0' + (val.tabIndex + 2)
      const params = { placeType, upPlaceCode: val.value }
      rqtGetPlaceChildrenByType(params)
        .then(res => {
          let resData = res.data.data
          if (val.tabIndex < 1) {
            this.initChildren(resData)
          }
          let child = findTreeNodeQuickly(this.dataRes, 'placeCode', val.value)
          this.initChild(child, resData)
        })
        .catch(() => {})
    },
    onConfirmClick(val) {
      const addr = []
      for (const item of val.selectedOptions) {
        addr.push({
          placeName: item.placeName,
          placeType: item.placeType,
          placeCode: item.placeCode,
          upPlaceCode: item.upPlaceCode
        })
      }
      this.$emit('onSelectedChange', addr)
      this.show = false
    },
    onCancelClick() {
      this.show = false
    }
  }
}
</script>
